<template>
  <div class="announcement-list">
    <a-spin :spinning="loading">
      <div v-if="announcements.length === 0" class="empty-state">
        <a-empty description="暂无公告" />
      </div>
      
      <div v-else class="announcement-items">
        <div
          v-for="announcement in announcements"
          :key="announcement.id"
          class="announcement-item"
          :class="{
            'is-top': announcement.isTop === 1,
            'is-unread': !announcement.isRead,
            'is-urgent': announcement.type === 1
          }"
          @click="handleItemClick(announcement)"
        >
          <div class="announcement-header">
            <div class="announcement-title">
              <a-tag v-if="announcement.isTop === 1" color="red" class="top-tag">
                置顶
              </a-tag>
              <a-tag 
                :color="getTypeColor(announcement.type)" 
                class="type-tag"
              >
                {{ getTypeText(announcement.type) }}
              </a-tag>
              <span class="title-text">{{ announcement.title }}</span>
              <a-badge v-if="!announcement.isRead" status="error" class="unread-badge" />
            </div>
            <div class="announcement-meta">
              <span class="publish-time">
                {{ formatTime(announcement.publishTime) }}
              </span>
            </div>
          </div>
          
          <div class="announcement-content">
            {{ announcement.content }}
          </div>
          
          <div class="announcement-click-hint">
            <span class="click-text">点击查看详情</span>
            <span class="click-arrow">→</span>
          </div>
          
          <div class="announcement-footer">
            <span class="publisher">
              发布者：{{ announcement.user?.userName || '未知' }}
            </span>
            <span v-if="announcement.expireTime" class="expire-time">
              过期时间：{{ formatTime(announcement.expireTime) }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-wrap">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          :show-size-changer="false"
          :show-quick-jumper="true"
          @change="handlePageChange"
        />
      </div>
    </a-spin>
  </div>

  <!-- 公告详情模态框 -->
  <AnnouncementDetailModal
    v-model:open="showDetailModal"
    :announcement="selectedAnnouncement"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { listPublicAnnouncements, markAsRead, type AnnouncementVO } from '@/api/announcementController'
import { announcementWebSocket } from '@/utils/announcementWebSocket'
import AnnouncementDetailModal from '@/components/AnnouncementDetailModal.vue'
import dayjs from 'dayjs'

interface Emits {
  (e: 'itemClick', announcement: AnnouncementVO): void
  (e: 'unreadCountChange', count: number): void
}

const emit = defineEmits<Emits>()

const loading = ref(false)
const announcements = ref<AnnouncementVO[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情模态框相关
const showDetailModal = ref(false)
const selectedAnnouncement = ref<AnnouncementVO | null>(null)

const loadAnnouncements = async () => {
  try {
    loading.value = true
    const response = await listPublicAnnouncements({
      current: currentPage.value,
      pageSize: pageSize.value,
      status: 1 // 只获取已发布的公告
    })
    
    announcements.value = response.data.data.records || []
    total.value = parseInt(response.data.data.total) || 0
    
    // 计算未读数量
    const unreadCount = announcements.value.filter(item => !item.isRead).length
    emit('unreadCountChange', unreadCount)
  } catch (error) {
    console.error('加载公告失败:', error)
    message.error('加载公告失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadAnnouncements()
}

const handleItemClick = async (announcement: AnnouncementVO) => {
  // 如果未读，标记为已读
  if (!announcement.isRead) {
    try {
      await markAsRead(announcement.id)
      announcement.isRead = true
      
      // 减少WebSocket中的未读数量
      announcementWebSocket.decreaseUnreadCount()
      
      // 重新计算未读数量
      const unreadCount = announcements.value.filter(item => !item.isRead).length
      emit('unreadCountChange', unreadCount)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 显示详情模态框
  selectedAnnouncement.value = announcement
  showDetailModal.value = true
  
  emit('itemClick', announcement)
}

const getTypeColor = (type: number) => {
  const colors = {
    0: 'blue',    // 普通公告
    1: 'red',     // 紧急公告
    2: 'orange'   // 维护公告
  }
  return colors[type as keyof typeof colors] || 'blue'
}

const getTypeText = (type: number) => {
  const texts = {
    0: '普通',
    1: '紧急',
    2: '维护'
  }
  return texts[type as keyof typeof texts] || '普通'
}

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 刷新公告列表的方法
const refresh = () => {
  currentPage.value = 1
  loadAnnouncements()
}

// 暴露刷新方法供父组件调用
defineExpose({
  refresh
})

onMounted(() => {
  loadAnnouncements()
  
  // 监听新公告
  announcementWebSocket.onNewAnnouncement(() => {
    // 有新公告时刷新列表
    loadAnnouncements()
  })
})
</script>

<style scoped>
.announcement-list {
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.announcement-items {
  space-y: 12px;
}

.announcement-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.announcement-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.announcement-item.is-top {
  border-color: #ff4d4f;
  background: linear-gradient(135deg, #fff 0%, #fff2f0 100%);
}

.announcement-item.is-unread {
  border-left: 4px solid #1890ff;
  background: linear-gradient(135deg, #fff 0%, #f6ffed 100%);
}

.announcement-item.is-urgent {
  border-color: #ff4d4f;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.announcement-title {
  display: flex;
  align-items: center;
  flex: 1;
}

.top-tag {
  margin-right: 8px;
}

.type-tag {
  margin-right: 8px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  flex: 1;
}

.unread-badge {
  margin-left: 8px;
}

.announcement-meta {
  display: flex;
  align-items: center;
  color: #8c8c8c;
  font-size: 12px;
}

.publish-time {
  white-space: nowrap;
}

.announcement-content {
  color: #595959;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.announcement-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8c8c8c;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.publisher {
  color: #1890ff;
}

.expire-time {
  color: #faad14;
}

.announcement-click-hint {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 4px;
  margin-top: 8px;
  color: #666;
  font-size: 12px;
  opacity: 0.7;
  transition: all 0.3s ease;
}

.announcement-item:hover .announcement-click-hint {
  opacity: 1;
  color: #1890ff;
}

.click-arrow {
  transition: transform 0.3s ease;
}

.announcement-item:hover .click-arrow {
  transform: translateX(2px);
}

.pagination-wrap {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

@media (max-width: 768px) {
  .announcement-list {
    padding: 8px;
  }
  
  .announcement-item {
    padding: 12px;
  }
  
  .announcement-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .announcement-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

/* 黑暗模式适配 */
[data-theme="dark"] .announcement-list {
  background: transparent;
}

[data-theme="dark"] .announcement-item {
  background: #262626;
  border-color: #404040;
  color: #ffffff;
}

[data-theme="dark"] .announcement-item:hover {
  background: #303030;
  border-color: #525252;
}

[data-theme="dark"] .announcement-item.is-unread {
  background: #1f2937;
  border-color: #3b82f6;
}

[data-theme="dark"] .announcement-item.is-urgent {
  background: #991b1b;
  border-color: #dc2626;
}

[data-theme="dark"] .title-text {
  color: #ffffff;
}

[data-theme="dark"] .announcement-content {
  color: #d1d5db;
}

[data-theme="dark"] .publish-time,
[data-theme="dark"] .publisher,
[data-theme="dark"] .expire-time {
  color: #9ca3af;
}

[data-theme="dark"] .empty-state {
  color: #9ca3af;
}

[data-theme="dark"] .announcement-click-hint {
  color: #9ca3af;
}

[data-theme="dark"] .announcement-item:hover .announcement-click-hint {
  color: #3b82f6;
}
</style>
